package saxion.speelveld.spaceengineer.database;

import java.util.ArrayList;

import saxion.speelveld.spaceengineer.model.ResourceType;
import saxion.speelveld.spaceengineer.model.TradeDeal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TradeDealsDAO
{
	private SQLiteDatabase database;

	private TradeDealsDB dbHelper;

	public TradeDealsDAO(Context context)
	{
		dbHelper = new TradeDealsDB(context);
	}

	/**
	 * Open the database connection.
	 * 
	 * @throws SQLException
	 */
	public void open() throws SQLException
	{
		database = dbHelper.getWritableDatabase();
	}

	/**
	 * Close the database connection.
	 */
	public void close()
	{
		dbHelper.close();
	}

	public void addTradeDealForPlanet(int planetId, ResourceType resourceType, int cost)
	{
		ContentValues values = new ContentValues();
		values.put(TradeDealsDB.COLUMN_PLANETID, planetId);
		values.put(TradeDealsDB.COLUMN_RESOURCETYPE, resourceType.ordinal());
		values.put(TradeDealsDB.COLUMN_RESOURCECOST, cost);
		database.insert(TradeDealsDB.TABLE_NAME, null, values);
	}

	public ArrayList<TradeDeal> getAllTradeDealsForPlanet(int planetId)
	{
		ArrayList<TradeDeal> listOfTradeDeals = new ArrayList<TradeDeal>();

		Cursor cursor = database.rawQuery("SELECT * FROM " + TradeDealsDB.TABLE_NAME + " WHERE "
			+ TradeDealsDB.COLUMN_PLANETID + " = " + planetId, null);

		cursor.moveToFirst();

		while (cursor.isAfterLast() == false)
		{
			listOfTradeDeals.add(cursorToTradeDeal(cursor));
			cursor.moveToNext();
		}

		cursor.close();
		return listOfTradeDeals;
	}

	private TradeDeal cursorToTradeDeal(Cursor cursor)
	{
		TradeDeal tradeDeal = null;

		int iResourceType = cursor.getInt(cursor.getColumnIndex(TradeDealsDB.COLUMN_RESOURCETYPE));
		int resourceCost = cursor.getInt(cursor.getColumnIndex(TradeDealsDB.COLUMN_RESOURCECOST));
		ResourceType resourceType = ResourceType.values()[iResourceType];
		tradeDeal = new TradeDeal(resourceType, 200, resourceCost);

		return tradeDeal;
	}

	public void beginTransactionMode()
	{
		database.beginTransaction();
	}

	public void setTransactionModeSuccesfull()
	{
		database.setTransactionSuccessful();
	}

	public void endTransactionMode()
	{
		database.endTransaction();
	}
}
